﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Service.Entity.Helper;
using RiderShop.Mobile.Common.Component;
using Kevin.Shop.Business.Core.Member;
using System.Web.Mvc;
using RiderShop.Mobile.Common.Component.OAuth.Weixing;
using RiderShop.Mobile.Modle;
using RiderShop.Mobile.Modle.MyAccount;
using RiderShop.Mobile.Common.Helper;
using System.IO;

namespace RiderShop.Mobile.Controllers
{
    public partial class CustomerController : ThemeController
    {
        /// <summary>
        /// 鲜享卡预约
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult XianXiangCardSubscribe()
        {
            //本地测试条件为了忽略WeixingOAuth
            var testopenId = Request.QueryString["openId"];
            if (!string.IsNullOrEmpty(testopenId))
            {
                WebClientContext.Current.OpenId = testopenId;
            }

            UserBasicInfo userInfo = new UserBasicInfo();
            //1.cookie中openid没有值
            if (string.IsNullOrEmpty(WebClientContext.Current.OpenId))
            {
                //2.获取微信信息
                var weixinInfo = WeixingOAuth.GetWeixinOAuthInfo();
                //3.获取不到微信信息
                if (weixinInfo == null || string.IsNullOrEmpty(weixinInfo.openid))
                {
                    return new EmptyResult();
                }
                //4.cookie写入openid
                WebClientContext.Current.OpenId = weixinInfo.openid;
            }
            //5.cookie中本身openid有值或cookie中写入了openid
            userInfo.ThirdUserId = "weixing_" + WebClientContext.Current.OpenId;

            //6.如果根据openId能查出这个user & 这个user是鲜享家会员，那么写票据,转向不带表单的鲜享卡界面
            var existUserInfo = GerUserByThirdId(userInfo.ThirdUserId);
            int userRank = 0;
            if (existUserInfo != null && existUserInfo.UserId > 0)
            {
                var userByUserId = CacheUsers.Get(existUserInfo.UserId, false);
                userRank = userByUserId.UserRank.HasValue ? userByUserId.UserRank.Value : 0;
            }
            //要么是预约卡成为鲜享家会员或者是通过画报注册来的。
            if (existUserInfo != null && existUserInfo.UserId > 0 && !String.IsNullOrEmpty(existUserInfo.UserName)
                && (existUserInfo.MSN == "XianxiangVIP" || userRank == 7))
            {
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(existUserInfo.UserName, true);
                KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
                WebClientContext.Current.GetCurrentUser();

                return View("~/Views/Customer/XianXiangCardSubscribeView.cshtml", userInfo);
            }

            //7.不是鲜享家会员跳转到鲜享家注册界面
            //不继承母版页
            return View("~/Views/Customer/XianXiangCardSubscribe.cshtml", userInfo);
        }

        /// <summary>
        /// 通过openId得到user
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public UserBasicInfo GerUserByThirdId(string openid)
        {
            var userList = new List<UserBasicInfo>();
            string urlGetUser = SiteUrl.FormatUrl("Common_GetUserInfoByThirdId", openid);
            if (!string.IsNullOrEmpty(openid))
            {
                userList = RestfulHelper.Query<UserBasicInfo>(urlGetUser);
            }
            //用户信息已经存在于我们的用户表里
            if (userList != null && userList.Count > 0 && userList[0].UserId > 0)
            {
                return userList[0];
            }

            //微信认证成功，但是用户未绑定
            return null;
        }

        /// <summary>
        /// 鲜享卡VIP注册
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RegisterXianXiangByAjaxRequest(UserBasicInfo user)
        {
            user.MSN = "XianxiangVIP";
            user.Password = "111111";
            if (!String.IsNullOrEmpty(user.ThirdUserId))
            {
                Kevin.Comm.Logger.Tracer.TraceLog("RegisterXianxiangByAjaxRequest:thirdUserId:" + user.ThirdUserId, "Register Xianxiang By AjaxRequest", "RegisterXianxiangByAjaxRequest", true);

                var userInfo = GerUserByThirdId(user.ThirdUserId);
                //openId存在用户
                if (userInfo != null && userInfo.UserId > 0 && !String.IsNullOrEmpty(userInfo.UserName))
                {
                    userInfo = CacheUsers.Get(userInfo.UserName, true);
                    //userInfo = CacheUsers.Get(userInfo.UserId, true);

                    userInfo.Address = user.Address;
                    userInfo.MSN = user.MSN;
                    userInfo.RegionId = user.RegionId;
                    userInfo.RealName = user.RealName;
                    userInfo.CellPhone = user.CellPhone;
                    Kevin.Comm.Logger.Tracer.TraceLog("RegisterXianxiangByAjaxRequest:thirdUserId exist:" + user.ThirdUserId, "Register Xianxiang By AjaxRequest", "RegisterXianxiangByAjaxRequest", true);

                    //更新user
                    ServiceResponser responser = MyAccountModel.UpdateUser(userInfo);
                    if (!responser.Status)
                    {
                        return Json(new { Status = false, ErrorMessage = responser.ErrorMessage });
                    }

                    HttpCookie AuthCookie = FormsAuthentication.GetAuthCookie(userInfo.UserName, true);
                    KevinCookieManager.Set(AuthCookie.Name, AuthCookie.Value, 10000);
                    WebClientContext.Current.GetCurrentUser();

                    return Json(new { Status = true, Operate = "update" });
                }
            }

            if (!String.IsNullOrEmpty(user.CellPhone))
            {
                var userInfo = CacheUsers.Get(user.CellPhone, true);
                //电话号码存在user
                if (userInfo != null && userInfo.UserId > 0)
                {
                    userInfo.Address = user.Address;
                    userInfo.MSN = user.MSN;
                    userInfo.RegionId = user.RegionId;
                    userInfo.RealName = user.RealName;
                    userInfo.CellPhone = user.CellPhone;
                    userInfo.ThirdUserId = user.ThirdUserId;
                    Kevin.Comm.Logger.Tracer.TraceLog("RegisterXianxiangByAjaxRequest:cellPhone exist:" + user.CellPhone, "Register Xianxiang By AjaxRequest", "RegisterXianxiangByAjaxRequest", true);

                    //更新user
                    ServiceResponser responser = MyAccountModel.UpdateUser(userInfo);
                    if (!responser.Status)
                    {
                        return Json(new { Status = false, ErrorMessage = responser.ErrorMessage });
                    }

                    HttpCookie AuthCookie = FormsAuthentication.GetAuthCookie(userInfo.UserName, true);
                    KevinCookieManager.Set(AuthCookie.Name, AuthCookie.Value, 10000);
                    WebClientContext.Current.GetCurrentUser();

                    return Json(new { Status = true, Operate = "update" });
                }
            }

            var model = new CustomerModel();
            //注册
            model.Register(user);

            if (!model.Result.Status)
            {
                return Json(new { Status = false, ErrorMessage = model.Result.ErrorMessage });
            }
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user.UserName, true);
            KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
            WebClientContext.Current.GetCurrentUser();

            return Json(new { Status = true, Operate = "create" });
        }

        /// <summary>
        /// 选择鲜享卡号
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public ActionResult XianXiangCardSelect(int type = -1, int status = -1)
        {
            var model = new CustomerModel();
            model.GetXianXiangCard(type, status);

            return View(WebClientContext.Current.SiteTheme, "Customer", "XianXiangCardSelect", WebClientContext.Current.CacheKeyDefaultMasterPage, model);

            //不继承母版页
            //return View("~/Views/Customer/XianXiangCardSelect.cshtml");
        }

        /// <summary>
        /// 选择鲜享卡号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult XianXiangCardSelectByAjaxRequest(int type = -1, int status = -1)
        {
            var model = new CustomerModel();
            model.GetXianXiangCard(type, status);

            return PartialView("~/Themes/rongji/Views/Customer/XianXiangCardSelectPartial.cshtml", model);
        }

        /// <summary>
        /// 提交选择的鲜享卡号
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public ActionResult XianXiangCardNumberSumbit(string cardNumber)
        {
            if (string.IsNullOrEmpty(cardNumber))
            {
                return new EmptyResult();
            }

            var model = new CustomerModel();
            model.SelectedXianXiangCardNumberCount = cardNumber.Split(',').Length;
            model.GetXianXiangCardByUserId();

            return View(WebClientContext.Current.SiteTheme, "Customer", "XianXiangCardNumberSumbit", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        /// <summary>
        /// 提交选择的鲜享卡号
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public ActionResult XianXiangCardNumberSumbitByAjaxRequest(string cardNumber)
        {
            if (string.IsNullOrEmpty(cardNumber))
            {
                return Json(new { Status = false, ErrorMessage = "noCardNumber" }, JsonRequestBehavior.AllowGet);
            }

            int sumbitCount = cardNumber.Split(',').Length;
            if (sumbitCount > 2)
            {
                return Json(new { Status = false, ErrorMessage = "每次只能选择两张卡" }, JsonRequestBehavior.AllowGet);
            }

            var model = new CustomerModel();
            var result = model.SubscribeXianXiangCard(cardNumber);
            if (!result.Status)
            {
                return Json(new { Status = false, ErrorMessage = result.ErrorMessage }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { Status = true, ErrorMessage = "submitSuccessfully" }, JsonRequestBehavior.AllowGet);
        }
    }
}
